//
//  CaptureVC.m
//  Lrjh
//
//  Created by jun on 2025/7/22.
//

#import <AVFoundation/AVFoundation.h>
#import "CaptureVC.h"
#import "WGS84ToGCJ02.h"
#import "JzdxLocationVC.h"
#import <Photos/Photos.h>

@interface CaptureVC ()<JzdxLocationVCDelegate,AVCapturePhotoCaptureDelegate>
@property (weak, nonatomic) IBOutlet UIView *viewCamera;

// 相机组件
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureDeviceInput *deviceInput;
@property (nonatomic, strong) AVCapturePhotoOutput *photoOutput;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (weak, nonatomic) IBOutlet UILabel *labLon;
@property (weak, nonatomic) IBOutlet UILabel *labLat;
@property (weak, nonatomic) IBOutlet UILabel *labAddress;

@end

@implementation CaptureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self checkCameraPermission];
}

- (void)checkCameraPermission {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status) {
        case AVAuthorizationStatusAuthorized:
            [self setupCamera];
            break;
        case AVAuthorizationStatusNotDetermined:
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self setupCamera];
                    });
                }
            }];
            break;
    }
}

- (void)setupCamera {
    // 1. 创建会话
    _captureSession = [[AVCaptureSession alloc] init];
    _captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
    
    // 2. 设置输入设备
    AVCaptureDevice *cameraDevice = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera
                                                                     mediaType:AVMediaTypeVideo
                                                                      position:AVCaptureDevicePositionFront];
    
    NSError *error;
    _deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:cameraDevice error:&error];
    
    if (!error && [_captureSession canAddInput:_deviceInput]) {
        [_captureSession addInput:_deviceInput];
    } else {
        NSLog(@"摄像头初始化失败: %@", error);
        return;
    }
    
    // 3. 设置输出
    _photoOutput = [[AVCapturePhotoOutput alloc] init];
    if ([_captureSession canAddOutput:_photoOutput]) {
        [_captureSession addOutput:_photoOutput];
    }
    
    // 4. 创建预览层
    _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
    _previewLayer.frame = self.viewCamera.layer.bounds;
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.viewCamera.layer addSublayer:_previewLayer];
}

// 在视图布局变化时更新预览层
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    // 更新预览层frame
    [CATransaction begin];
    [CATransaction setDisableActions:YES]; // 禁止动画
    
    _previewLayer.frame = self.viewCamera.bounds;
    
    // 更新设备方向
    [self updateVideoOrientation];
    
    [CATransaction commit];
}

// 更新视频方向
- (void)updateVideoOrientation {
    AVCaptureConnection *previewConnection = [_previewLayer connection];
    if ([previewConnection isVideoOrientationSupported]) {
        [previewConnection setVideoOrientation:[self currentVideoOrientation]];
    }
}

// 获取当前视频方向
- (AVCaptureVideoOrientation)currentVideoOrientation {
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    
    if (deviceOrientation == UIDeviceOrientationLandscapeLeft) {
        return AVCaptureVideoOrientationLandscapeRight;
    } else if (deviceOrientation == UIDeviceOrientationLandscapeRight) {
        return AVCaptureVideoOrientationLandscapeLeft;
    } else if (deviceOrientation == UIDeviceOrientationPortraitUpsideDown) {
        return AVCaptureVideoOrientationPortraitUpsideDown;
    } else {
        // 默认竖屏
        return AVCaptureVideoOrientationPortrait;
    }
}

- (void)startCameraSession {
    if (!_captureSession.isRunning) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self.captureSession startRunning];
        });
    }
}

- (void)stopCameraSession {
    if (_captureSession.isRunning) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self.captureSession stopRunning];
        });
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self startCameraSession];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self stopCameraSession];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (IBAction)onClose:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onLocation:(id)sender {
    JzdxLocationVC *vc = [JzdxLocationVC new];
    vc.delegate =self;
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)onLocation:(NSString *)lat lon:(NSString *)lon address:(NSString *)address{
    double latitude = [lat doubleValue];
    double longitude = [lon doubleValue];
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
    CLLocationCoordinate2D coo = [WGS84ToGCJ02 transformFromWGS84ToGCJ02:coordinate];
    self.labLat.text = [self formatLatitude:coo.latitude];
    self.labLon.text = [self formatLongitude:coo.longitude];
    self.labAddress.text = address;
}


-(NSString *)formatLatitude:(double)latitude {
    
    int degrees = (int)latitude;
    double minutesDecimal = fabs((latitude - degrees) * 60);
    int minutes = (int)(minutesDecimal + 0.5); // 四舍五入

    // 保留两位整数，且不足补0
    return [NSString stringWithFormat:@"%d°%02d", degrees, minutes];
}

-(NSString *)formatLongitude:(double)longitude {
    
    int degrees = (int)longitude;
    double minutesDecimal = fabs((longitude - degrees) * 60);
    int minutes = (int)(minutesDecimal + 0.5); // 四舍五入

    // 保留一位整数
    return [NSString stringWithFormat:@"%d°%d", degrees, minutes];
}
- (IBAction)onCamera:(id)sender {
    
    AVCapturePhotoSettings *settings = [AVCapturePhotoSettings photoSettings];
   settings.flashMode = AVCaptureFlashModeAuto;
   [_photoOutput capturePhotoWithSettings:settings delegate:self];

}

- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error {
    if (error) {
        NSLog(@"拍照处理失败: %@", error);
        return;
    }
    
    // 获取原始图片
    NSData *imageData = [photo fileDataRepresentation];
    UIImage *originalImage = [UIImage imageWithData:imageData];
    
    // 添加水印
    UIImage *watermarkedImage = [self addWatermarkToImage:originalImage];
    
    // 保存图片
    [self saveImage:watermarkedImage];
}

// 添加水印
- (UIImage *)addWatermarkToImage:(UIImage *)originalImage {
    // 调整图片尺寸
    CGSize targetSize = CGSizeMake(1080, 1440);
    UIGraphicsBeginImageContext(targetSize);
    [originalImage drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height)];
    
    NSShadow *textShadow = [[NSShadow alloc] init];
    textShadow.shadowColor = [UIColor grayColor];       // 阴影颜色
    textShadow.shadowOffset = CGSizeMake(1, 1);         // 偏移量 (width, height)
    textShadow.shadowBlurRadius = 1.0;                  // 模糊度
    
    // 设置文字属性
    NSDictionary *textAttributes = @{
        NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Thin" size:80],
        NSForegroundColorAttributeName: [UIColor whiteColor],
        NSStrokeColorAttributeName: [UIColor lightGrayColor],
        NSShadowAttributeName:textShadow,
        NSStrokeWidthAttributeName: @-0.5
    };
    
    // 设置文字属性
    NSDictionary *tipAttributes = @{
        NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light" size:66],
        NSForegroundColorAttributeName: [UIColor whiteColor],
        NSStrokeColorAttributeName: [UIColor lightGrayColor],
        NSStrokeWidthAttributeName: @-0.5
    };
    
    [@"北纬" drawAtPoint:CGPointMake(50, 60) withAttributes:tipAttributes];
    
    [self.labLat.text drawAtPoint:CGPointMake(50, 130) withAttributes:textAttributes];
    
    [@"东经" drawAtPoint:CGPointMake(50, 260) withAttributes:tipAttributes];
    
    [self.labLon.text drawAtPoint:CGPointMake(50, 330) withAttributes:textAttributes];
    
//    // 左上角：经纬度
//    NSString *gpsInfo = [NSString stringWithFormat:@"经度: %@\n纬度: %@",
//                         self.labLat.text,
//                         self.labLon.text];
//    [gpsInfo drawAtPoint:CGPointMake(20, 20) withAttributes:textAttributes];
    
    
  
    // 创建段落样式
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; // 尾部截断，显示省略号
    // 设置文字属性
    NSDictionary *timeAttributes = @{
        NSFontAttributeName: [UIFont systemFontOfSize:50],
        NSForegroundColorAttributeName: [UIColor whiteColor],
        NSStrokeColorAttributeName: [UIColor lightGrayColor],
        NSParagraphStyleAttributeName: paragraphStyle,
        NSStrokeWidthAttributeName: @-0.5
    };
    
    // 左下角：时间地点
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy.MM.dd"];
    NSString *timeInfo = [formatter stringFromDate:[NSDate date]];
    NSString *locationInfo = [NSString stringWithFormat:@"%@\n%@", timeInfo, self.labAddress.text ?: @"未知位置"];
    
    
    CGSize textSize = [locationInfo sizeWithAttributes:timeAttributes];
    CGRect rect = CGRectMake(50, targetSize.height - textSize.height - 70, targetSize.width - 150, textSize.height);
//    [locationInfo drawAtPoint:CGPointMake(50, targetSize.height - textSize.height - 70)
//               withAttributes:timeAttributes];
    
    [locationInfo drawInRect:rect withAttributes:timeAttributes];
    
    // 设置文字属性
    NSDictionary *waterAttributes = @{
        NSFontAttributeName: [UIFont systemFontOfSize:35],
        NSForegroundColorAttributeName: [UIColor whiteColor],
        NSStrokeColorAttributeName: [UIColor grayColor],
        NSStrokeWidthAttributeName: @-0.8
    };
    
    // 右下角：水印文字
    NSString *watermarkText = @"水印相机";
    CGSize watermarkSize = [watermarkText sizeWithAttributes:waterAttributes];
    [watermarkText drawAtPoint:CGPointMake(targetSize.width - watermarkSize.width - 30,
                                          targetSize.height - watermarkSize.height - 30)
                withAttributes:waterAttributes];
    
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return result;
}

// 保存图片并控制大小
- (void)saveImage:(UIImage *)image {
    CGFloat compression = 0.9f;
    NSData *imageData = nil;
    
    // 循环调整压缩率
    for (int i = 0; i < 6; i++) {
        imageData = UIImageJPEGRepresentation(image, compression);
        if (imageData.length < 500 * 1024) break; // 500KB以内
        compression -= 0.15f;
    }
    
    // 保存到相册
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:[UIImage imageWithData:imageData]];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            NSLog(@"保存成功！大小: %.2fKB", imageData.length/1024.0);
                    
            dispatch_async(dispatch_get_main_queue(), ^{
                [self toast:@"保存成功"];
            });
        }
    }];
}

@end
